<template>
  <div class="base-content">
    <div class="basic-info">
      <el-form ref="filterForm" :model="filterForm" inline>
        <el-form-item label="报告编号" prop="reportNum">
          <el-input
            v-model="filterForm.reportNum"
            placeholder="报告编号"
            clearable
          />
        </el-form-item>
        <el-form-item label="委托单号" prop="entrustOrderNum">
          <el-input
            v-model="filterForm.entrustOrderNum"
            placeholder="委托单号"
            clearable
          />
        </el-form-item>
        <el-form-item label="样品名称" prop="sampleName">
          <el-input
            v-model="filterForm.sampleName"
            placeholder="样品名称"
            clearable
          />
        </el-form-item>
        <el-form-item class="base-filter-button">
          <el-button
            v-loading="searchLoading"
            type="primary"
            @click="getList('filter')"
            >查询</el-button
          >
          <el-button @click="cancelForm">清空</el-button>
        </el-form-item>
      </el-form>
      <div class="base-content-operate">
        <el-button
          icon="el-icon-document-copy"
          type="primary"
          @click="approval()"
          >进入审批</el-button
        >
        <el-button
          v-rights="'BatchDownLoad'"
          icon="el-icon-document-copy"
          type="primary"
          @click="downLoad()"
          >批量下载</el-button
        >
        <el-button
          v-rights="'Withdrawal'"
          icon="el-icon-document-copy"
          type="primary"
          @click="withdrawal()"
          >报告撤回</el-button
        >
        <!-- <el-button
          v-rights="'UpLoad'"
          icon="el-icon-document-copy"
          type="primary"
          @click="upLoad()"
          >上传</el-button
        >
        <el-button
          v-rights="'Export'"
          icon="el-icon-document-copy"
          type="primary"
          @click="exportData()"
          >导出</el-button
        > -->
      </div>
      <el-table
        ref="table"
        v-loading="tableLoad"
        :data="tableData"
        fit
        highlight-current-row
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="reportNum" label="报告编号"> </el-table-column>
        <el-table-column prop="orderNum" label="委托单号"></el-table-column>
        <el-table-column prop="reportStatus" label="报告状态">
        </el-table-column>
        <el-table-column prop="reportType" label="报告形式"> </el-table-column>
        <el-table-column prop="sampleName" label="样品名称"> </el-table-column>
        <el-table-column prop="compilePersonName" label="编写人" />
        <el-table-column prop="compileDateString" label="编写日期" />
        <el-table-column prop="remark" label="备注" />
        <el-table-column label="操作" width="140">
          <template slot-scope="scope">
            <div class="base-table-operation">
              <el-link
                v-rights="'Upload'"
                type="primary"
                @click="uploadReport(scope.row)"
                >上传</el-link
              >
              <el-link
                v-rights="'Preview'"
                type="primary"
                @click="previewReport(scope.row)"
                >预览</el-link
              >
              <el-link
                type="primary"
                :disabled="scope.row.reportStatusCode != 30"
                @click="downLoadFile(scope.row)"
                >下载</el-link
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <BasePagination
        :total="total"
        :current-page="pagination.pageIndex"
        @changePage="changePage"
        @sizeChange="sizeChange"
      />
      <ReportPreviewDialog
        v-if="previewDialogVisible"
        :dialog-visible.sync="previewDialogVisible"
        :report-html.sync="reportHtml"
      />
      <ReportStandingBookDialog
        v-if="dialogFormVisible"
        :dialog-form-visible.sync="dialogFormVisible"
        :report-id.sync="reportId"
        :down-load-disabled.sync="downLoadDisabled"
      />
      <BasePreviewFile
        v-if="previewFileShow"
        :preview-file-show.sync="previewFileShow"
        :preview-file.sync="filepreview"
      />
      <ReportWithdrawalDialog
        v-if="withdrawalDialogFormVisible"
        :withdrawal-dialog-form-visible.sync="withdrawalDialogFormVisible"
        :report-ids="reportIds"
        :sample-registration-ids="sampleRegistrationIds"
      />
    </div>
  </div>
</template>
<script>
// import PreviewFileDialog from "@/ModuleEntrust/views/EntrustManage/EntrustOrder/PreviewFileDialog.vue";
// import ModuleEntrust from "panna-module-entrust";
import saverFile from "file-saver";
import { mapGetters } from "vuex";
import {
  getList,
  ReportVerify,
  Get,
  DownloadReportZip,
} from "../../../api/Report/ReportManage";
import ReportPreviewDialog from "./ReportPreviewDialog.vue";
import htmlDocx from "html-docx-js/dist/html-docx";
import ReportStandingBookDialog from "./ReportStandingBookDialog.vue";
import { GetStaticFileInfo } from "@/api/Base";
import ReportWithdrawalDialog from "../../../components/ReportTemplate/ReportWithdrawalDialog.vue";
export default {
  name: "ReportStandingBookList",
  components: {
    ReportStandingBookDialog,
    // previewFileDialog: ModuleEntrust ? ModuleEntrust.PreviewFileDialog : null,
    ReportPreviewDialog,
    ReportWithdrawalDialog,
  },
  data() {
    return {
      downLoadDisabled: false,
      reportHtml: "",
      previewDialogVisible: false,
      previewFileShow: false,
      dialogFormVisible: false,
      searchLoading: false,
      tableLoad: false,
      withdrawalDialogFormVisible: false,
      reportId: "",
      filepreview: {
        fileName: "",
        url: "",
        storageFileName: "",
        urlList: [],
      },
      filterForm: {
        reportNum: "",
        entrustOrderNum: "",
        sampleName: "",
        entrustOrderId: 0,
      },
      tableData: [],
      tableDatas: [],
      pagination: {
        pageIndex: 1,
        pageSize: 10,
      },
      total: 0,
      reportData: [],
      reportIds: [],
      sampleRegistrationIds: [],
    };
  },
  computed: {
    ...mapGetters(["fileDomain", "fileBucket"]),
  },
  created() {
    if (this.$route.query.ReportNum !== undefined) {
      this.filterForm.reportNum = this.$route.query.ReportNum;
    }
    if (
      this.$route.query !== null &&
      this.$route.query.entrustOrderId !== undefined &&
      this.$route.query.entrustOrderId !== null &&
      this.$route.query.entrustOrderId !== 0
    ) {
      this.filterForm.entrustOrderId = this.$route.query.entrustOrderId;
    }
    this.getList();
  },
  methods: {
    // 批量下载
    downLoad() {
      if (this.tableDatas.length === 0 || this.tableDatas === null) {
        this.$message.error("请选择数据");
        return false;
      }

      var idList = [];
      for (let i = 0; i < this.tableDatas.length; i++) {
        if (this.tableDatas[i].reportStatusCode !== 30) {
          this.$message.error("请选择审核通过数据");
          return false;
        }
        idList.push(this.tableDatas[i].id);
      }

      DownloadReportZip({ idList: idList }).then((res) => {
        var blob = new Blob([res.data], {
          type: "application/octet-stream",
        });
        var url = window.URL.createObjectURL(blob);
        const link = document.createElement("a"); // 创建a标签
        link.href = url;
        link.download = "报告.zip"; // 重命名文件
        link.click();
        URL.revokeObjectURL(url); // 释放内存
      });
    },

    // 下载
    downLoadFile(data) {
      // 查询报告数据
      var downLoadName = data.reportNum + ".pdf";
      Get({ id: data.id }).then((res) => {
        if (res.code === 200) {
          this.reportData = res.data;
          if (this.reportData.reportPDFUrl) {
            var fileUrl = `${this.reportData.reportPDFUrl}`;
            GetStaticFileInfo(fileUrl, downLoadName);
          } else {
            if (this.reportData.reportUrl != null) {
              var fileUrls = `${this.reportData.reportUrl}`;
              GetStaticFileInfo(fileUrls, this.reportData.reportFileName);
            } else {
              const converted = htmlDocx.asBlob(this.reportData.reportFile);
              saverFile(
                converted,
                this.reportData.reportTemplateName + ".docx"
              );
            }
          }
        }
      });
    },
    // 下载文件js模拟点击a标签进行下载
    saveAs(blob, filename) {
      var link = document.createElement("a");
      link.href = window.URL.createObjectURL(blob);
      link.download = filename;
      link.click();
    },
    // 通过文件下载url拿到对应的blob对象
    getBlob(url) {
      return new Promise((resolve) => {
        const xhr = new XMLHttpRequest();
        xhr.open("GET", url, true);
        xhr.responseType = "blob";
        xhr.onload = () => {
          if (xhr.status === 200) {
            resolve(xhr.response);
          }
        };

        xhr.send();
      });
    },
    withdrawal() {
      if (this.tableDatas === null || this.tableDatas.length === 0) {
        this.$message.error("请选择数据");
        return false;
      }
      this.reportIds = [];
      var flag = true;
      this.tableDatas.forEach((element) => {
        if (element.reportStatusCode === 31) {
          // 报告撤回
          this.$message.error(element.reportNum + "数据已撤回，请重新选择");
          flag = false;
          return;
        }
        this.reportIds.push(element.id);
      });
      if (flag) {
        this.withdrawalDialogFormVisible = true;
      }

      // console.log(
      //   "withdrawalDialogFormVisible",
      //   this.withdrawalDialogFormVisible
      // );
    },
    // 进入审批
    approval() {
      if (this.tableDatas === null || this.tableDatas.length === 0) {
        this.$message.error("请选择数据");
        return false;
      }
      // if (this.tableDatas.length > 1) {
      //   this.$message.error("请选择一条数据");
      //   return false;
      // }

      for (let i = 0; i < this.tableDatas.length; i++) {
        if (this.tableDatas[i].reportStatusCode !== 10) {
          this.$message.error("请选择待审核数据");
          return false;
        }
      }
      var data = [];
      for (var j = 0; j < this.tableDatas.length; j++) {
        var obj = {};
        obj.auditDataId = this.tableDatas[j].id;
        data.push(obj);
      }

      ReportVerify(data).then((res) => {
        this.getList();
      });
    },
    // 上传
    uploadReport(row) {
      if (row.reportStatusCode > 10) {
        this.$message.error("此数据状态暂不允许上传报告");
        return;
      }
      this.reportId = row.id;

      this.downLoadDisabled = Number(row.reportStatusCode) !== 30;

      this.dialogFormVisible = true;
    },

    // 預覽報告
    previewReport(row) {
      Get({ id: row.id }).then((res) => {
        if (res.code === 200) {
          this.filepreview.urlList = res.data.urlList;
          if (row.reportUrl !== null && row.reportUrl !== "") {
            this.filepreview.fileName = row.reportFileName;
            this.filepreview.url = row.reportUrl;
            this.filepreview.storageFileName = row.reportFileName;
            this.filepreview.type = "img";
            this.previewFileShow = true;
          } else {
            this.reportHtml = row.reportFile;
            this.previewDialogVisible = true;
          }
        }
      });
    },
    // 导出
    exportData() {},
    getList(flag) {
      if (flag) {
        this.pagination.pageIndex = 1;
      }
      this.loading = true;
      getList({ ...this.filterForm, ...this.pagination })
        .then((res) => {
          this.tableData = res.data.dataList ? res.data.dataList : [];
          this.total = res.data.total;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    handleSelectionChange(val) {
      this.tableDatas = val;
    },
    // 清空筛选条件
    cancelForm() {
      this.filterForm.entrustOrderId = 0;
      this.$refs.filterForm.resetFields();
      this.getList("filter");
    },
    changePage(page) {
      this.pagination.pageIndex = page;
      this.getList();
    },
    sizeChange(val) {
      this.pagination.pageIndex = 1;
      this.pagination.pageSize = val;
      this.getList();
    },
  },
};
</script>
